
import 'package:flutter/material.dart';

import 'frame_animation_image.dart';

class CustomBottomNavigationBar extends StatefulWidget {

  CustomBottomNavigationBar({
    super.key,
    required this.items,
    this.currentIndex = 0,
    this.onTap,
    this.backgroundColor,
    this.selectedItemColor,
    this.unselectedItemColor
  });

  final List<ItemEntity> items;
  final int currentIndex;
  final ValueChanged<int>? onTap;
  final Color? backgroundColor;
  final Color? selectedItemColor;
  final Color? unselectedItemColor;

  @override
  State<CustomBottomNavigationBar> createState() => _BottomNavigationBarState();
}

class _BottomNavigationBarState extends State<CustomBottomNavigationBar> with TickerProviderStateMixin {

  var items = <Widget>[];

  @override
  void initState() {
    super.initState();
    for(var i = 0; i < widget.items.length; i++){
      items.add(Item(i==widget.currentIndex,widget.items[i],(){ widget.onTap?.call(i);}));
    }

  }

  @override
  Widget build(BuildContext context) {
    return DecoratedBox(
        decoration: BoxDecoration(
            color: const Color(0xff000000),
            border: Border.all( width: 0),
            boxShadow: [
              BoxShadow(
                blurRadius: 6 ,
                blurStyle: BlurStyle.outer,
              )
            ]
        ),
        child: Flex(
            direction: Axis.horizontal,
            children: items
        )
    );
  }

  @override
  void didUpdateWidget(covariant CustomBottomNavigationBar oldWidget) {
    super.didUpdateWidget(oldWidget);
    items.replaceRange(oldWidget.currentIndex, oldWidget.currentIndex+1, [
      Item(false,widget.items[oldWidget.currentIndex],(){ oldWidget.onTap?.call(oldWidget.currentIndex);})]);
    items.replaceRange(widget.currentIndex, widget.currentIndex+1, [
      Item(true,widget.items[widget.currentIndex],(){ widget.onTap?.call(widget.currentIndex);})
    ]);
  }

}

class Item extends StatelessWidget{
  Item(this.isSelect, this.item, this.onTap);

  final bool isSelect;
  final ItemEntity item;
  final ValueGetter onTap;

  @override
  Widget build(BuildContext context) {
    return Expanded(
      flex: 1,
      child: InkWell(
        onTap:onTap,
        child: Padding(
          padding: EdgeInsets.all(9),
          child: isSelect ?
          FrameAnimationImage(item.control, item.select, width: 36, height: 36, start: true, interval: 50)
              : Image.asset(item.unSelect, width: 36, height: 36),
        ),
      ),
    );
  }
}

class ItemEntity{

  String unSelect;
  List<String> select;
  String label;
  GlobalKey<FrameAnimationImageState> control;
  int interval;

  ItemEntity(this.unSelect, this.select, this.label,this.control,this.interval);
}
